/**
 *  Abstract REST Adaptor to house the basic functionalities
 *  common to all types of REST adaptors 
 *
 *  @author Scott Monahan
 *  @version $Id$
 *  
 *  File last changed on $Date:$ by $Author:$ in $Rev:$
 *
 */

package info637.pprc.adaptor;

import info637.pprc.ErrorCodes;
import info637.pprc.processors.RestEndpointMappingProcessor;
import info637.pprc.services.ISessionService;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstractRESTAdaptor extends RestEndpointMappingProcessor {
	
	@Autowired 
	private ISessionService sessionService = null;
	
	protected String errorCodesToString(List<ErrorCodes> errorCodes) {
		
		StringBuffer out = new StringBuffer();
		boolean firstError = true;
		
		for (ErrorCodes errorCode : errorCodes) {
			
			if (!firstError) {
				
				out.append("|");
				
			} else {
				
				firstError = false;
			}
			
			out.append(errorCode.asString());
		}
		
		return out.toString();
	}
	
	protected boolean isStringValid(String valToCheck) {
		
		if (valToCheck == null || valToCheck.length() == 0) {
			
			return false;
			
		} else {
			
			return true;
		}
	}
	
	protected List<ErrorCodes> validateBaseRequest(String requestId) {
		
		List<ErrorCodes> errors = new ArrayList<ErrorCodes>();
		
		if (!isStringValid(requestId)) {
			
			errors.add(ErrorCodes.REQUEST_ID_REQUIRED);
		}
		
		return errors;
	}
	
	protected List<ErrorCodes> validateSessionRequest(String requestId, String sessionId) {
		
		List<ErrorCodes> errors = validateBaseRequest(requestId);
		
		if (!isStringValid(sessionId)) {
			
			errors.add(ErrorCodes.SESSION_ID_REQUIRED);
			
		} else {
			
			if (sessionService.isSessionValid(sessionId)) {
				
				sessionService.updateLastAccessed(sessionId);
				
			} else {
				
				errors.add(ErrorCodes.SESSION_EXPIRED);
			}
		}
		
		return errors;
	}
	
	protected boolean validateNumeric(String val) {
		
		boolean retVal = false;
		
		try {
			
			Long.parseLong(val);
			
			retVal = true;
			
		} catch (Exception ex) { ; }
		
		return retVal;
	}
}
